<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24" class="top">
        <el-form :model="searchParams" ref="searchParams" :inline="true">
          <el-form-item label="订单号" prop="orderId">
            <el-input class="input" v-model="searchParams.orderId" maxlength='30' placeholder="请输入" clearable
              show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="买家ID" prop="memberCode">
              <el-input v-model="searchParams.memberCode" maxlength='11' placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="买家手机号" prop="memberPhone">
              <el-input v-model="searchParams.memberPhone" maxlength='11' placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="上级ID" prop="parentCode">
              <el-input v-model="searchParams.parentCode" maxlength='11' placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="提货方式" prop="sendType">
              <el-select v-model="searchParams.sendType" placeholder="请选择" clearable>
                <el-option v-for="item in formData.options.sendTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="支付方式" prop="payway">
              <el-select v-model="searchParams.payway" placeholder="请选择" clearable>
                <el-option v-for="item in formData.options.payways" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="searchParams.orderStatus" placeholder="请选择" clearable>
                <el-option v-for="item in formData.options.orderStatus" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="dates" label="支付时间">
              <el-date-picker
                  @change="changeTime"
                  v-model="dateRange"
                  type="daterange"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  >
                  </el-date-picker>
            </el-form-item>
          <el-form-item>
            <el-button @click="handleSearch" type="primary" icon="el-icon-search"
              style="margin-left:40px">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-form :model="searchParams" ref="searchParams" :inline="true" style="margin:10px 0">
          <el-button @click="operateAction('export', {})" type="primary" plain size='small'>导出</el-button>
          <el-button @click="operateAction('exportForSendItem', {})" type="success" plain size='small' v-if="$route.name=='suborder' || $route.name=='payForFranchiseeOrder'">导出批量发货模版</el-button>
          <el-button @click="operateAction('importForSendItem', {})" type="warning" plain size='small' v-if="$route.name=='suborder' || $route.name=='payForFranchiseeOrder'">导入批量发货模版</el-button>
        </el-form>
        <el-table :data="dataList" size='medium' ref="multipleTable" @selection-change="handleSelectionChange" border>
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="orderId" label="订单号" width="240"></el-table-column>
          <el-table-column label="商品信息" prop="itemModel" :show-overflow-tooltip="true" width="200px">
              <template slot-scope="{ row, index }">
                <div v-if="row.scene == 'payForFranchisee'">[店内收款]</div>
                <div v-else v-for="(item, index) in row.itemList" :key="index">
                  <div style="display: flex;flex-direction: row;">
                    <img :src="item.coverUrl" width="60px" height="60px" />
                    <div style="line-height: 20px;">
                      <jc-button v-if="item.itemName" :title="item.itemName" @click="showItemDetail(item)"></jc-button>
                      <div style="font-size: 14px;margin-left: 10px;">ID：{{ item.item }}</div>
                      <div style="font-size: 14px;margin-left: 10px;">{{ formData.getSpecs(item.specValues) }}</div>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          <el-table-column prop="orderStatusLabel" label="订单状态" show-overflow-tooltip></el-table-column>
          <el-table-column prop="realPay" label="订单金额（元）" show-overflow-tooltip width="100px">
            <template slot-scope="{row, index}">
              <div v-if="row.incomes>0">¥{{ count.mul(row.sellingPrice, 1) }}+{{ count.mul(row.incomes, 1) }}积分</div>
              <div v-else>¥{{ count.mul(row.sellingPrice, 1) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="realPay" label="实付金额（元）" show-overflow-tooltip width="100px">
            <template slot-scope="{row, index}">
              <div v-if="row.incomes>0">¥{{ count.mul(row.realPay, 1) }}+{{ count.mul(row.incomes, 1) }}积分</div>
              <div v-else>¥{{ count.mul(row.realPay, 1) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="costPrice" label="成本" show-overflow-tooltip></el-table-column>
          <el-table-column prop="paywayLabel" label="支付类型" show-overflow-tooltip></el-table-column>
          <el-table-column prop="payTime" label="支付时间" width="160">
            <template slot-scope="{row, index}">
              {{ formatTime.dateFormat('YY-MM-DD hh:mm:ss', row.payTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="userModel" label="买家信息" width="180px">
            <template slot-scope="{row, index}">
              <div>ID：{{ row.userModel.code }}</div>
              <div>手机号：{{ row.userModel.phone }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="shopModel.name" label="商户" show-overflow-tooltip></el-table-column>
          <el-table-column prop="sendTypeLabel" label="发货类型" show-overflow-tooltip></el-table-column>
          <el-table-column prop="remark" label="买家备注" show-overflow-tooltip></el-table-column>
          <el-table-column prop="remark_seller" label="卖家备注" show-overflow-tooltip></el-table-column>

          <el-table-column prop="redact" label="操作" fixed="right" width="120">
            <template slot-scope="{ row, index }">
              <el-button type="text" @click="operateAction('sendItem', row)" size='medium' v-if="row.orderStatus=='WAIT_SEND'&&($route.name=='suborder' || $route.name=='payForFranchiseeOrder')">发货</el-button>
              <el-button type="text" @click="operateAction('updateRemark', row)" size='medium'>备注</el-button>
              <el-button type="text" @click="operateAction('detail', row)" size='medium'>详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination style="background: #ffffff; height: 50px" v-show="totalSize > 0" :total="totalSize"
          :page.sync="page" :limit.sync="size" @pagination="getDataList" />
      </el-col>
    </el-row>
    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!-- <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px" @click="exportTemplate"
            >下载模板</el-link
          >
        </div> -->
        <div class="el-upload__tip" style="color:red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <sendItem ref="sendItem" @confirm='getDataList'></sendItem>
    <updateRemarkDialog title="备注" ref="updateRemarkDialog" @confirm='getDataList'></updateRemarkDialog>
    <orderDetailView ref="orderDetailView"></orderDetailView>
  </div>
</template>

<script>
import { formData } from './data'
import { findOrderList, exportExcel, exportExcelForSendItem } from '@/api/pay/order.js'
import updateRemarkDialog from './components/updateRemarkDialog.vue'
import { Loading } from 'element-ui';
import orderDetailView from '@/views/pay/order/components/orderDetailView.vue'
import sendItem from '@/views/pay/order/components/sendItem.vue'
import { getToken } from '@/utils/auth'
export default {
  components: { updateRemarkDialog, orderDetailView, sendItem },
  data() {
    return {
      page: 1,
      size: 10,
      totalSize: 0,
      dataList: [],
      searchParams: {},
      multipleSelection: [],
      formData,
      dateRange: [],
      fullscreenLoading: null,
      pickerOptions: {
        shortcuts: [{
          text: '最近7天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近30天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近365天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 1);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'token ' + getToken()},
        // 上传的地址
        url: '/api/pay/order/importExcelForSendItem/'
      },
    }
  },
  created() {
    this.getDataList()
    this.changeTime()
  },
  methods: {
    handleSearch() {
      this.page = 1
      this.getDataList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    showItemDetail(val){

    },
    changeTime(){
      if(this.dateRange && this.dateRange.length>0){
        this.searchParams.startTime = this.dateRange[0]
        this.searchParams.endTime = this.dateRange[1]
      }else{
        this.searchParams.startTime = ''
        this.searchParams.endTime = ''
      }
    },
    operateAction(scene, row) {
      switch (scene) {
        case 'export':
          var rowIds = this.multipleSelection.map(function (item) {
            return item.id
          })
          if(rowIds.length>0){
            this.searchParams.ids = rowIds
          }else{
            this.searchParams.ids = []
          }
          this.fullscreenLoading = Loading.service({ fullscreen: true, text: '订单正在加工中，请稍后！' });
          this.searchParams.routerName = this.$route.name
          exportExcel(this.searchParams).then(res => {
              this.fullscreenLoading.close()
              const link = document.createElement('a');
              let blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel'
              });
              link.href = URL.createObjectURL(blob);
              var filename = this.formatTime.dateFormat('YYYYMMDDhhmmss', Date.now())
              link.download = '订单明细' + filename + '.xlsx';
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
          })
          break;
        case 'exportForSendItem':
          var rowIds = this.multipleSelection.map(function (item) {
            return item.id
          })
          if(rowIds.length>0){
            this.searchParams.ids = rowIds
          }else{
            this.searchParams.ids = []
          }
          this.fullscreenLoading = Loading.service({ fullscreen: true, text: '批量发货模版正在加工中，请稍后！' });
          this.searchParams.routerName = this.$route.name
          exportExcelForSendItem(this.searchParams).then(res => {
            this.fullscreenLoading.close()
              const link = document.createElement('a');
              let blob = new Blob([res.data], {
              type: 'application/vnd.ms-excel'
              });
              link.href = URL.createObjectURL(blob);
              var filename = this.formatTime.dateFormat('YYYYMMDDhhmmss', Date.now())
              link.download = '批量发货模版' + filename + '.xlsx';
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
          })
          break;
        case 'importForSendItem':
          this.upload.title = '订单导入'
          this.upload.open = true
          break;
        case 'updateRemark':
          this.$refs.updateRemarkDialog.show({rowId: row.id})
          break;
        case 'detail':
          this.$refs.orderDetailView.show({rowId: row.id})
          break;
        case 'sendItem':
        this.$refs.sendItem.show(row.orderId, 'sendItem')
          break;
        case 'delete':
          if (this.multipleSelection.length <= 0) {
            this.$message({
              message: '请选择操作行',
              type: 'info'
            })
          } else {
            var rowIds = this.multipleSelection.map(function (item) {
              return item.id
            })
            var _this = this
            this.$confirm('是否确认删除选中的' + rowIds.length + '条记录?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function () {
              return deleteOrders({
                obj_ids: rowIds
              }).then(res => {
                if (res.data.code == 10000) {
                  _this.getDataList()
                  _this.$message({
                    message: '操作成功',
                    type: 'success'
                  })
                }
              })
            })
          }
          break;
        default:
          break;
      }
    },
    //数据请求-----------------------------------------------
    // 获取列表数据
    getDataList() {
      this.searchParams.page = this.page
      this.searchParams.size = this.size
      // if(this.$route.name == 'orderList'){
      //   this.searchParams.scene = 'generay'
      // }else if(this.$route.name == 'orderForGoldCustom'){
      //   this.searchParams.scene = 'goldCustom'
      // }
      this.searchParams.routerName = this.$route.name
      findOrderList(this.searchParams).then(res => {
        if (res.data.code == 10000) {
          this.totalSize = res.data.data.total_count
          this.dataList = res.data.data.list
        }
      });
    },
    // 下载模板操作 ------------------------------------------
    exportTemplate() {
      window.location.href = 'https://oss.higo8.top/common/订单导入模板.xlsx'
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      var res = response
      console.log('res', res)
      if(res.code == 10000){
        this.$message({
          message: res.data,
          type: 'success',
          duration: 2 * 1000
        })
      }else if(res.code == 10001){
        if(res.data.repetitionList.length>0){
          this.$refs.showRepetitionUser.show(res.data)
        }else{
          this.$alert('成功导入' + res.data.successCount + '条数据', '导入结果', { dangerouslyUseHTMLString: true })
        }
      }else if(res.code == 10002){
        this.$message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
      }
      
      this.getDataList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
  },
}
</script>


<style lang="scss" scoped></style>
